//自定义插件模板
import axios from 'axios'

//Vue.prototype.$axios=axios

axios.defaults.baseURL='http://localhost:5000/';//配置请求根路径
//axios.defaults.baseURL='http://hhmy.ngrok2.xiaomiqiu.cn/';//配置请求根路径
//axios.defaults.baseURL='sapi';//配置请求根路径
axios.defaults.timeout = 30000; //设置请求时间
// 添加请求拦截器，在请求头中加token
axios.interceptors.request.use(
  config => {
    if (localStorage.getItem('mytoken')) {
      config.headers.mytoken = localStorage.getItem('mytoken');
    }
 
    return config;
  },
  error => {
    return Promise.reject(error);
  })
//http reponse拦截器
  axios.interceptors.response.use(
    response =>{
      switch(response.data.code){
        case 401:
          localStorage.removeItem('mytoken');
          router.push('/login');
      }
      return response;
    },
    error=>{
      console(error)
      if(error.response){
        switch(error.response.status){
          case 401:
            localStorage.removeItem('mytoken');
            router.push('/login');
            // router.replace({
            //   path: '/views/login',
            //   query: {redirect: router.currentRoute.fullPath}//登录成功后跳入浏览的当前页面
            // })
        }
      }
   
    }
  )



/**
 * 封装get方法
 * @param url
 * @param data
 * @returns {Promise}
*/
export function fetch(url,params={}){
    return new Promise((resolve,reject) => {
      const loading = this.$loading({
        lock: true,
        text: 'Loading',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      });
      axios.get(url,{
        params:params
      })
      .then(response => {
        loading.close();
        resolve(response.data);
      })
      .catch(err => {
        loading.close();
        reject(err)
      })
    })
  }
/**
 * 封装post请求
 * @param url
 * @param data
 * @returns {Promise}
 */
 
export function post(url,data={}){
    return new Promise((resolve,reject)=>{
      const loading = this.$loading({
        lock: true,
        text: 'Loading',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      });
        axios.post(url,data).then(response=>{
          loading.close();
            resolve(response.data);
        })
        .catch(err=>{
          loading.close();
          this.$alert("网路异常")
          reject(err);
        })
    })

}

export function postupload(url,data=new FormData()){
  return new Promise((resolve,reject)=>{
    const loading = this.$loading({
      lock: true,
      text: 'Loading',
      spinner: 'el-icon-loading',
      background: 'rgba(0, 0, 0, 0.7)'
    });
      axios.post(url,data).then(response=>{
        loading.close();
          resolve(response.data);
      })
      .catch(err=>{
        loading.close();
        this.$alert("网路异常")
        reject(err);
      })
  })

}